// pages/ShopOwnerPages/addGood/addGood.js
var util = require('../../../utils/util')
var editor = require('../../../common/editorBehavior/editor/editor')
Page({
  behaviors: [editor],
  data: {
    editorPlaceHolder: '请输入...',
    pickerLoading: false,
    typePicker: false,
    discountPicker: false,
    isSubmit: false,
    editorOpen: false,
    fieldArr1: [{
        dataName: 'goods_name',
        border: true,
        type: 'text',
        maxlength: 20,
        isLink: false,
        placeHolder: '请输入服务名称',
        value: '',
        error: false,
        inputAlign: 'left',
        disabled: false,
        label: '服务名称'
      },
      {
        dataName: 'goods_sub_name',
        type: 'text',
        maxlength: 50,
        border: true,
        isLink: false,
        placeHolder: '请输入服务副标题',
        value: '',
        error: false,
        inputAlign: 'left',
        disabled: false,
        label: '服务副标'
      },
      {
        dataName: 'sort',
        type: 'number',
        maxlength: 11,
        border: true,
        isLink: false,
        placeHolder: '请输入排序权重（数值越大越靠前）',
        value: '',
        error: false,
        inputAlign: 'left',
        disabled: false,
        label: '服务排序'
      },
      {
        dataName: 'cate_id',
        type: 'text',
        maxlength: 50,
        border: true,
        isLink: true,
        placeHolder: '请选择服务分类',
        disabled: false,
        value: '',
        error: false,
        inputAlign: 'left',
        label: '服务分类',
        text: ''
      },
    ],
    fieldArr2: [{
        dataName: 'price',
        type: 'number',
        maxlength: 50,
        border: true,
        isLink: false,
        placeHolder: '请输入服务价格',
        disabled: false,
        value: '',
        error: false,
        inputAlign: 'left',
        label: '服务价格'
      },
      {
        dataName: 'stock',
        border: true,
        type: 'number',
        maxlength: 6,
        isLink: false,
        placeHolder: '请输入服务库存',
        disabled: false,
        value: '',
        error: false,
        inputAlign: 'left',
        label: '服务库存'
      },
      {
        dataName: 'is_discount',
        disabled: false,
        type: 'text',
        border: true,
        isLink: true,
        placeHolder: '请选择是否折扣',
        value: '',
        text: '',
        error: false,
        inputAlign: 'left',
        label: '折扣'
      },
      {
        dataName: 'goods_detail',
        disabled: false,
        type: 'text',
        border: true,
        isLink: true,
        placeHolder: '请编辑服务详情及细节',
        value: '',
        text: '',
        error: false,
        inputAlign: 'left',
        label: '服务详情'
      },
    ],
    upImgArr: [{
        title: '服务主图',
        max: 1,
        fileList: [],
        option: 'goods'
      },
      {
        title: '服务轮播图',
        max: 5,
        fileList: [],
        option: 'goods'
      }
    ],
    discountColumn: [{
        text: '是',
        code: 1
      },
      {
        text: '否',
        code: 2
      },
    ],
  },

  fieldFocus(e) {
    // console.log(e)
    let key = e.currentTarget.dataset.key;
    this.setData({
      [`${key}.error`]: false,
    })
  },
  fieldBlur(e) {
    let key = e.currentTarget.dataset.key;
    let value = e.detail.value;
    let cursor = e.detail.cursor;
    // console.log(e)
    this.setData({
      [`${key}.error`]: cursor === 0,
      [`${key}.value`]: value,
    })
  },
  fieldTap(e) {
    // console.log(e)
    let group = e.currentTarget.dataset.group;
    let i = e.currentTarget.dataset.index;
    // let key = e.currentTarget.dataset.key;
    if (group == 'fieldArr1') {
      if (i === 3) {
        this.setData({
          typePicker: true,
          pickerLoading: true,
        })
        //获取选项数据
        util.sendRequest('goods/cate', 'GET').then(res => {
          if (res.data.code === 0) {
            this.setData({
              typeColumn: res.data.result,
              pickerLoading: false
            })
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        })
      }
    } else if (group == 'fieldArr2') {
      if (i === 2) {
        this.setData({
          discountPicker: true
        })
      } else if (i === 3) {
        this.setData({
          editorOpen: !this.data.editorOpen,
          [`fieldArr2[3].text`]: this.data.fieldArr1[3].value && this.data.editorOpen ? '已保存，点击继续编辑' : '关闭将自动保存',
          [`fieldArr2[3].text`]: this.data.editorOpen ? '已保存，点击继续编辑' : '关闭将自动保存',
        })
      }
    }
  },
  showNotice() {
    wx.showModal({
      confirmColor: "#FF325B",
      showCancel: false,
      title: '温馨提示',
      content: '排序权重值：请输入整数，该数值越大，服务在店铺的排序越靠前，默认值为0。',
      cancelText: '好的',
    })
  },

  onClose() {
    this.setData({
      discountPicker: false,
      typePicker: false,
    })
  },

  onTypeConfirm(e) {
    // console.log(e)
    this.setData({
      [`fieldArr1[3].text`]: e.detail.value.cate_name,
      [`fieldArr1[3].value`]: e.detail.value.cate_id,
      [`fieldArr1[3].error`]: false,
      typePicker: false
    })
  },
  onDiscountConfirm(e) {
    this.setData({
      [`fieldArr2[2].text`]: e.detail.value.text,
      [`fieldArr2[2].value`]: e.detail.value.code,
      [`fieldArr2[2].error`]: false,
      discountPicker: false
    })
  },

  // console.log(this.data)
  afterRead(event) {
    let index = event.currentTarget.dataset.index;
    const file = event.detail.file;
    // console.log(file);
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: getApp().globalData.urls + 'api/image/upload',
      filePath: file.url,
      name: 'file',
      formData: {
        option: this.data.upImgArr[index].option
      },
      success: (res) => {
        if (res.statusCode === 200) {
          let data = JSON.parse(res.data)
          // console.log(data)
          // 上传完成需要更新 fileList
          var fileList = []
          if (this.data.upImgArr[index].fileList) {
            fileList = this.data.upImgArr[index].fileList
          }
          fileList.push({
            ...file,
            url: getApp().globalData.urls + data.pic
          });
          this.setData({
            [`upImgArr[${index}].fileList`]: fileList
          });
          // console.log(this.data.upImgArr)
        }
      },
      fail: (res) => {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },
  beforeRead(e) {
    const {
      file,
      callback
    } = e.detail;
    // console.log(file.type)
    file.type === 'image' ?
      callback(true) :
      wx.showToast({
        title: '请选择图片文件',
        icon: 'none'
      })
  },
  overSize() {
    wx.showToast({
      title: '图片太大了,最大支持2M哦~',
      icon: 'none'
    })
  },
  deleteUpImg(e) {
    // console.log(e)
    let index = e.currentTarget.dataset.index;
    var fileList = this.data.upImgArr[index].fileList;
    let i = e.detail.index;
    fileList.splice(i, 1);
    // console.log(fileList)
    this.setData({
      [`upImgArr[${index}].fileList`]: fileList
    })
  },

  //数据处理方法
  TranslateToStr(arr) {
    //将menuArr中的图片数据转换成服务器所需要的Str数据  arr:指定的fileList
    //服务器需求去掉url字段，并用 ， 分隔
    // 用法： this.TranslateToStr(this.data.upImgArr[0].fileList)
    var result = ''
    var urls = getApp().globalData.urls
    if (arr.length > 0) {
      for (let i in arr) {
        let imgstr = arr[i].url.replace(urls, '');
        if (i < arr.length - 1) {
          result = result + imgstr + ','
        } else {
          result = result + imgstr
        }
      }
    }
    return result
  },

  getValue(n) {
    //根据dataName将表格内容转换成对象
    var data = {}
    for (let item of n) {
      data[item.dataName] = item.value
    }
    return data
  },

  addGood() {
    // 判断是否符合条件
    console.log(this.data.fieldArr1, this.data.fieldArr2, this.data.editorHtml, this.data.upImgArr)
    var count = 0;
    for (let i in this.data.fieldArr1) {
      if (this.data.fieldArr1[i].value.length === 0) {
        this.setData({
          [`fieldArr1[${i}].error`]: true,
        })
        wx.showToast({
          title: this.data.fieldArr1[i].placeHolder,
          icon: 'none'
        })
        break
      } else {
        count++
        this.setData({
          [`fieldArr1[${i}].error`]: false,
        })
      }
    }
    if (!(count === 4)) {
      return
    }
    for (let i in this.data.fieldArr2) {
      if (this.data.fieldArr2[i].value.length === 0) {
        if (i === 3) {
          this.setData({
            [`fieldArr2[${i}].text`]: '请编辑服务详情及细节',
            [`fieldArr2[${i}].error`]: true,
          })
        } else {
          this.setData({
            [`fieldArr2[${i}].error`]: true,
          })
        }
        wx.showToast({
          title: this.data.fieldArr2[i].placeHolder,
          icon: 'none'
        })
        break
      } else {
        count++
        this.setData({
          [`fieldArr2[${i}].error`]: false,
        })
      }
    }
    if (!(count === 8)) {
      return
    }
    //判断是否按照要求上传了图片
    for (let i in this.data.upImgArr) {
      if (this.data.upImgArr[i].fileList.length === 0) {
        wx.showToast({
          title: '请上传' + this.data.upImgArr[i].title,
          icon: 'none'
        })
        break
      } else {
        count++
      }
    }
    // console.log(count)
    if (!this.data.isSubmit && count === 10) {
      this.setData({
        isSubmit: true
      })
      // 发送请求
      //处理表单信息
      let data1 = this.getValue(this.data.fieldArr1);
      let data2 = this.getValue(this.data.fieldArr2);
      //处理上传的图片数据
      // console.log(data1, data2)
      let data = Object.assign(data1, data2);
      data['goods_mian'] = this.TranslateToStr(this.data.upImgArr[0].fileList)
      data['goods_pic'] = this.TranslateToStr(this.data.upImgArr[1].fileList)
      console.log(data)
      util.sendRequest('shop/goodsadd', 'POST', data, 1).then(res => {
        if (res.data.code === 0) {
          this.setData({
            isSubmit: false
          })
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            success: () => {
              //显示商品审核状态页面
              wx.navigateTo({
                url: '/pages/ShopOwnerPages/goodApplyStatus/goodApplyStatus',
              })
            }
          })

        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      })
    }
  },

  //富文本转义
  html2Escape(str) {
    //去除urls
    var urls = getApp().globalData.urls
    str = str.replace(new RegExp(urls, 'gm'), "");
    //转义
    str = str.replace(/[<>&"]/g, function (c) {
      return {
        '<': '&lt;',
        '>': '&gt;',
        '&': '&amp;',
        '"': '&quot;'
      } [c];
    });
    return str
  },

  editorFocus() {
    this.setData({
      editorFocus: true,
      [`fieldArr2[3].error`]: false,
    })
  },
  editorBlur(e) {
    // console.log(e)
    this.setData({
      editorFocus: false
    })
    //每次失去焦点的时候都会保存一次html内容,
    // 需要将结果转义
    let result = this.html2Escape(e.detail.html)
    console.log(result)
    this.setData({
      [`fieldArr2[3].value`]: result,
    })
  },
  getHeight(el) {
    //获取元素高度
    let query = wx.createSelectorQuery();
    query.select(el).boundingClientRect(rect => {
      let height = rect.height;
      // console.log(height);
      this.setData({
        bottomHeight: height
      })
    }).exec();
  },

  onLoad: function (options) {
    this.getHeight('.bottom_btn_hover');
    this.setData({
      hoverHeightNotab: getApp().globalData.hoverHeightNotab,
      device: getApp().globalData.device
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})